package com.enjoy.mjbaseframe.okgo;

import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.enjoy.mjbaseframe.util.AppUtil;
import com.enjoy.mjbaseframe.util.BaseUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.OkUpload;
import com.lzy.okserver.upload.UploadTask;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.enjoy.mjbaseframe.constant.BaseVariable.BASE_URL;
import static com.enjoy.mjbaseframe.constant.BaseVariable.TOKEN;

/**
 * Created by Administrator on 2018/1/29.
 */

public class OkGoLoader {
    /**
     * 所有请求tag集合
     * 在onDestory中取消请求
     */
    public List<String> requestTags = new ArrayList<>();
    public void clearTags(){
        for(int i = 0 ; i < requestTags.size() ; i ++){
            Logger.d("TAG:"+requestTags.get(i));
            OkGo.getInstance().cancelTag(requestTags.get(i));
        }
        requestTags.clear();
    }

    private static volatile OkGoLoader singleton;
    public static OkGoLoader getInstance() {
        if (singleton == null) {
            synchronized (OkGoLoader.class) {
                if (singleton == null) {
                    singleton = new OkGoLoader();
                }
            }
        }
        return singleton;
    }

    /**
     * post请求
     * @param url 请求地址
     * @param map 参数map
     * @param callback  结果回调
     */
    public void post(String url, Map<String, String> map, JsonCallback callback){
        if (!BaseUtil.isNetworkConnected(AppUtil.getApp())) {
            Toast.makeText(AppUtil.getApp(),"网络异常，请稍后重试",Toast.LENGTH_LONG).show();
            return;
        }
        PostRequest request = OkGo.post(BASE_URL + url)
                .tag(url)
                .headers("accessToken", TOKEN)
                .isMultipart(false);       //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
        if (map!=null&&!map.isEmpty()) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey().toString();
                String value = entry.getValue().toString();
                Log.e("POST:", "key=" + key + " value=" + value);
                request.params(key, value);
            }
        }
        requestTags.add(url);//url作为该请求的tag
        request.execute(callback);
    }

    /**
     * get请求
     * @param url 请求地址
     * @param callback 结果回调
     */
    public void get(String url, JsonCallback callback) {
        if (!BaseUtil.isNetworkConnected(AppUtil.getApp())) {
            Toast.makeText(AppUtil.getApp(),"网络异常，请稍后重试",Toast.LENGTH_LONG).show();
            return;
        }
        get(url,null,callback);
    }

    /**
     * get请求
     * @param url 请求地址
     * @param map 参数map
     * @param callback 结果回调
     */
    public void get(String url,Map<String, String> map, JsonCallback callback) {
        requestTags.add(url);//url作为该请求的tag
        OkGo.get(BaseUtil.jsonToString(BASE_URL + url,map))//
                .tag(url)//
                .headers("accessToken", TOKEN)
                .execute(callback);
    }



    /**
     * 单文件上传
     * 多文件上传方案：1 解压缩 2 任务列表
     * @param uploadUrl  上传地址
     * @param uploadFile 上传资源地址
     * @param listener   上传状态监听
     */
    public void upload(String uploadUrl, String uploadFile, LogUploadListener listener){
        if (!BaseUtil.isNetworkConnected(AppUtil.getApp())) {
            Toast.makeText(AppUtil.getApp(),"网络异常，请稍后重试",Toast.LENGTH_LONG).show();
            return;
        }
        PostRequest<String> postRequest = OkGo.<String>post(BASE_URL + uploadUrl)//
                .params("fileKey0", new File(uploadFile))//
                .converter(new StringConvert());
        Random random = new Random();
        UploadTask<String> task = OkUpload.request(uploadFile, postRequest)//
                .priority(random.nextInt(100))//
                .register(listener)
                .save();
        task.start();
    }

    /**
     * 单文件下载
     * 多文件下载方案：1 解压缩 2 任务列表
     * @param apkUrl   资源下载地址
     * @param listener 下载状态监听
     */
    public void download(String apkUrl,LogDownloadListener listener){
        if (!BaseUtil.isNetworkConnected(AppUtil.getApp())) {
            Toast.makeText(AppUtil.getApp(),"网络异常，请稍后重试",Toast.LENGTH_LONG).show();
            return;
        }
        OkDownload.getInstance().setFolder(Environment.getExternalStorageDirectory().getAbsolutePath() + "/mj/");
        OkDownload.getInstance().getThreadPool().setCorePoolSize(3);
//        ApkBean apk = new ApkBean();
        //这里只是演示，表示请求可以传参，怎么传都行，和okgo使用方法一样
        GetRequest<File> request = OkGo.<File>get(BASE_URL + apkUrl)//
                .headers("aaa", "111")//
                .params("bbb", "222");

        //这里第一个参数是tag，代表下载任务的唯一标识，传任意字符串都行，需要保证唯一,我这里用url作为了tag
        OkDownload.request(apkUrl, request)//
                .priority(1000)//
                .save()//
                .register(listener)//
                .start();
    }
}
